package com.example.mq.mqserver;

import com.example.mq.common.*;
import com.example.mq.mqserver.core.BasicProperties;

import javax.xml.crypto.Data;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: DongGuoZhen
 * @Date: 2024/03/07/21:46
 * @Description: 中间人服务器  消息队列的本体服务器     本质上就是TCP服务器
 */
public class BrokerServer {
    private ServerSocket serverSocket;

    //当前一个brokerServer上只有一个虚拟主机
    private VirtualHost virtualHost = new VirtualHost("default");

    //使用这个hash表表示当前的所有会话(也就是说有那些客户端和服务器进行通信
    //key就是channelId,value就是对应的Socket对象
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<String, Socket>();

    //引用线程池来来处理多个客户端的请求
    private ExecutorService executorService = null;

    //引入一个boolean变量来控制服务器是否继续运行
    private volatile boolean runnable = true;

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("[BrokerServer] 启动!");
        executorService = Executors.newCachedThreadPool();
        try{
            while (runnable) {
                //处理每个客户端
                Socket clientSocket = serverSocket.accept();
                //把处理连接的逻辑,丢给这个线程池
                executorService.submit(() -> {
                    processConnection(clientSocket);
                });
            }
        } catch (SocketException e) {
            System.out.println("[BrokerServer] 服务器停止运行!");
            //e.printStackTrace();
        }

    }


    //停止服务器
    public void stop() throws IOException {
        runnable = false;
        //把线程池中的任务都放弃,线程都销毁
        executorService.shutdownNow();
        serverSocket.close();
    }

    //通过这个方法来处理一个客户端的连接
    //在这一个连接中,可能会涉及到多个请求和响应.
    private void processConnection(Socket clientSocket) {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            //从这个流对象中按照约定的应用层协议读取数据 就需要用到DataInputStream和DataOutputStream
            try (DataInputStream dataInputStream = new DataInputStream(inputStream);
                 DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                while (true) {
                    //1.读取请求并解析
                    Request request = readRequest(dataInputStream);
                    //2. 根据请求计算响应
                    Response response = process(request, clientSocket);
                    //3. 把响应写回给客户端
                    writeResponse(dataOutputStream, response);

                }
            }
        } catch (EOFException | SocketException e) {
            //对于这个代码来说,DataInputStream如果读到EOF,就会抛出一个EOFException异常
            //需要借助EOF来结束
            System.out.println("[BrokerServer] connection连接关闭! 客户端地址: "
                    + clientSocket.getInetAddress().toString() + ":" + clientSocket.getPort());
        } catch (IOException | ClassNotFoundException | MqException e) {
            System.out.println("[BrokerServer] connection连接出现异常");
            e.printStackTrace();
        } finally {
            try {
                //当连接处理完了,就关闭 socket
                clientSocket.close();
                //一个tcp连接中,可能包含多个channel,就需要把当前这个socket对应的所有channel都清理掉
                clearClosedSession(clientSocket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //读取请求并解析
    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        request.setType(dataInputStream.readInt()); //读4个字节
        request.setLength(dataInputStream.readInt()); //读length
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);  //实际读出来的长度
        if (n != request.getLength()) {
            throw new IOException("读取请求格式出错");
        }
        request.setPayload(payload); //把读到的数据写回request中
        return request;
    }


    //根据请求并计算响应
    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException, MqException {
        //1. 把request中的payload做一个解析
        //当前请求中的payload里面放的内容是根据type来走的
        //比如type是0x3,payload里面放的就是ExchangeDeclareArguments 以此类推
        //此处设定的不同的方法参数,虽然都有不同的类,但是都是继承自同一个BasicArguments
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(request.getPayload());
        System.out.println("[Request] rid=" + basicArguments.getRid() + ",channelId = " + basicArguments.getChannelId()
                + ",type=" + request.getType() + ",length=" + request.getLength());
        //2. 根据type的值,来进一步区分下次请求要干啥
        boolean ok = true;
        if (request.getType() == 0x1) {
            //创建channel
            sessions.put(basicArguments.getChannelId(), clientSocket);
            System.out.println("[BrokerServer] 创建channel完成! channelId=" + basicArguments.getChannelId());
        } else if (request.getType() == 0x2) {
            sessions.remove(basicArguments.getChannelId());
            System.out.println("[BrokerServer] 销毁channel完成! channelId=" + basicArguments.getChannelId());
        } else if (request.getType() == 0x3) {
            //创建交换机 此时payload就是ExchangeDeclareArguments
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            //此时就可以调用起来创建交换机的方法了
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(), arguments.getExchangeType(),
                    arguments.isDurable(), arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x4) {
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArguments;
            //销毁交换机
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
        } else if (request.getType() == 0x5) {
            //创建队列
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(arguments.getQueueName(), arguments.isDurable(), arguments.isExclusive(),
                    arguments.isAutoDelete(), arguments.getArguments());
        } else if (request.getType() == 0x6) {
            //销毁队列
            QueueDeleteArguments arguments = (QueueDeleteArguments) basicArguments;
            ok = virtualHost.queueDelete(arguments.getQueueName());
        } else if (request.getType() == 0x7) {
            //创建绑定
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(arguments.getQueueName(), arguments.getExchangeName(), arguments.getBindingKey());
        } else if (request.getType() == 0x8) {
            //销毁绑定
            QueueUnbindArguments arguments = (QueueUnbindArguments) basicArguments;
            ok = virtualHost.queueUnbind(arguments.getQueueName(), arguments.getExchangeName());
        } else if (request.getType() == 0x9) {
            //发送消息
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublish(arguments.getExchangeName(), arguments.getRoutingKey(),
                    arguments.getBasicProperties(), arguments.getBody());
        } else if (request.getType() == 0xa) {
            //订阅消息
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArguments;
            ok = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(),
                    new Consumer() {
                        //这个回调函数要做的工作就是把服务器收到的消息直接推送给对应的消费者客户端
                        @Override
                        public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                            //这里需要先知道当前这个收到的消息要交给谁,发给那个客户端
                            //此处的consumerTag其实是channelId,根据channelId去sessions中查询,
                            // 就可以得到对应的socket对象.就可以往里面发送数据了
                            //1. 根据channelId找到socket对象
                            Socket clientSocket = sessions.get(consumerTag);
                            if (clientSocket == null || clientSocket.isClosed()) {
                                throw new MqException("[BrokerServer] 订阅消息的客户端已经关闭!");
                            }
                            //2.构造响应数据
                            SubScribeReturns subScribeReturns = new SubScribeReturns();
                            subScribeReturns.setChannelId(consumerTag);
                            //此处只有响应,没有请求,所以不设置也没关系
                            subScribeReturns.setRid("");
                            subScribeReturns.setOk(true);
                            subScribeReturns.setConsumerTag(consumerTag);
                            subScribeReturns.setBody(body);
                            subScribeReturns.setBasicProperties(basicProperties);
                            byte[] payload = BinaryTool.toBytes(subScribeReturns);
                            Response response = new Response();
                            // 0xc表示服务器给消费者客户端推送的消息
                            response.setType(0xc);
                            // 此处response的payload就是SubScribeReturns
                            response.setLength(payload.length);
                            response.setPayload(payload);
                            //3. 把数据写回客户端
                            DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                            writeResponse(dataOutputStream, response);
                        }
                    });
        } else if (request.getType() == 0xb) {
            //调用basicAck确认消息
            BasicAckArguments arguments = (BasicAckArguments) basicArguments;
            ok = virtualHost.basicAck(arguments.getQueueName(), arguments.getMessageId());
        } else {
            //当前的type是非法的,
            throw new MqException("[BrokerServer] 未知的type! type = " + request.getType());
        }
        //3. 构造响应
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setChannelId(basicArguments.getChannelId());
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setOk(ok);
        byte[] payload = BinaryTool.toBytes(basicReturns);
        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        System.out.println("[Response] rid = " + basicReturns.getRid() + ",channelId = "
                + basicReturns.getChannelId() + ",type=" + request.getType() + ",length = " + response.getLength());
        return response;
    }

    //把响应写回给客户端
    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        dataOutputStream.flush(); //刷新缓冲区
    }

    //这里要遍历上述sessions hash表,把该关闭的socket对应的键值对都删除掉
    private void clearClosedSession(Socket clientSocket) {
        //存放要清理的所有channel
        List<String> toDeleteChannelId = new ArrayList<>();
        for (Map.Entry<String, Socket> entry : sessions.entrySet()) {
            if(entry.getValue() == clientSocket) {
                toDeleteChannelId.add(entry.getKey());
            }
        }
        for (String channelId: toDeleteChannelId) {
            sessions.remove(channelId);
        }
        System.out.println("[BrokerServer] 清理session完成! 被清理的channelId = " + toDeleteChannelId);
    }

}